writable-async-iterable-stream
An async stream which can be iterated over using a for-await-of loop and which can be written to.
The WritableAsyncIterableStream
class extends the AsyncIterableStream
class.
See https://github.com/SocketCluster/async-iterable-stream
Installation
npm install writable-async-iterable-stream
Usage
Consume a stream and write to it asynchronously:
let iterableStream = new WritableAsyncIterableStream();
async function consumeAsyncIterable(asyncIterable) {
for await (let packet of asyncIterable) {
console.log('Packet:', packet);
}
}
consumeAsyncIterable(iterableStream);
setInterval(() => {
iterableStream.write(`Timestamp: ${Date.now()}`);
}, 100);
Consume a filtered stream using an async generator:
let iterableStream = new WritableAsyncIterableStream();
async function* createFilteredStreamGenerator(fullStream, filterFunction) {
for await (let packet of fullStream) {
if (filterFunction(packet)) {
yield packet;
}
}
};
async function consumeAsyncIterable(asyncIterable) {
for await (let packet of asyncIterable) {
console.log('Packet:', packet);
}
}
function filterFn(data) {
return /5$/.test(data);
}
let filteredStreamGenerator = createFilteredStreamGenerator(iterableStream, filterFn);
consumeAsyncIterable(filteredStreamGenerator);
setInterval(() => {
iterableStream.write(`Timestamp: ${Date.now()}`);
}, 100);
Consume only the next data object which will be written to the stream:
let iterableStream = new WritableAsyncIterableStream();
(async () => {
let data = await iterableStream.once();
console.log(data);
})();
setInterval(() => {
iterableStream.write(`Timestamp: ${Date.now()}`);
}, 100);
See test/
directory for additional examples.